package com.anyonavinfo.cpaddemo.service.musicplayerservice;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.Log;

import com.anyonavinfo.cpaddemo.Application;
import com.anyonavinfo.cpaddemo.data.musicinfo.MusicInfo;
import com.anyonavinfo.cpaddemo.utils.ToastManagerUtils;

import java.io.File;
import java.util.ArrayList;

import static android.content.Context.AUDIO_SERVICE;

/**
 * Created by zza on 2017/2/10.
 */

public class MusicPlayerServiceHelper {

    private static ArrayList<MusicPlayerServiceCallBack> observerArrayList;
    private final Context mContext;

    private MediaPlayer player;
    private AudioManager mAudioManager;
    private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;
    private MusicInfo musicInfo;
    private static final int TIME_REFRESH_DELAY = 1000;
    private final Handler mHandler = new Handler();

    private static MusicPlayerServiceHelper INSTANCE = null;

    public static MusicPlayerServiceHelper getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MusicPlayerServiceHelper();
        }
        return INSTANCE;
    }

    private MusicPlayerServiceHelper() {
        observerArrayList = new ArrayList<>();
        mContext= Application.getContextObject();
        initAudioFocusChangeLister();
    }

    public void play(MusicInfo musicInfo) {
        if (this.musicInfo != null && this.musicInfo.getPath() == musicInfo.getPath()){
            if (!player.isPlaying()){
                player.start();
            }
        }else {
            this.musicInfo = musicInfo;
            prepare4Play();
            try {
                player.reset();
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        for(MusicPlayerServiceCallBack observer : observerArrayList){
                            observer.onMusicPlayBackEnding();
                        }
                    }
                });
                if (new File(musicInfo.getPath()).exists()){
                    player.setDataSource(musicInfo.getPath());
                    player.prepare();
                    //player.seekTo(pausePosition);
                    int result = mAudioManager.requestAudioFocus(audioFocusChangeListener
                            , AudioManager.STREAM_MUSIC
                            , AudioManager.AUDIOFOCUS_GAIN);
                    if (AudioManager.AUDIOFOCUS_REQUEST_GRANTED != result) {
                        return;
                    }
                    player.start();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //根据情况通知更新UI
            }
        }
        mHandler.post(mTimeRefresher);
    }


    private void prepare4Play() {
        if (player == null) {
            player = new MediaPlayer();
        }
        player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return true;
            }
        });
    }

    private void initAudioFocusChangeLister() {
        mAudioManager = (AudioManager) mContext.getSystemService(AUDIO_SERVICE);
        player = new MediaPlayer();
        audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                switch (focusChange) {
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                        pause();
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                        if (player != null) {
                            player.setVolume(0.5f, 0.5f);
                        }
                        break;
                    case AudioManager.AUDIOFOCUS_GAIN:
                        if (player != null) {
                            player.setVolume(1.0f, 1.0f);
                            if (!player.isPlaying()){
                                //play();
                            }
                        }
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS:
                        pause();
                        break;
                }
            }
        };
    }

    public void pause() {
        mHandler.removeCallbacks(mTimeRefresher);
        if (player.isPlaying()) {
            player.pause();
            //pausePosition = player.getCurrentPosition();
        }
    }

    public void stop() {
        mHandler.removeCallbacks(mTimeRefresher);
        if (player!=null && player.isPlaying()) {
            player.pause();
            player.release();
            player = null;
        }
        mAudioManager.abandonAudioFocus(audioFocusChangeListener);
    }

    public void changePlayProgress(int time){
        if (player != null){
            if (player.isPlaying()){
                pause();
            }
            player.seekTo(time);
            player.start();
            mHandler.post(mTimeRefresher);
        }
    }


    private  Runnable mTimeRefresher = new Runnable() {
        @Override
        public void run() {
            for(MusicPlayerServiceCallBack observer : observerArrayList){
                observer.updateProgress(player.getCurrentPosition(), player.getCurrentPosition()  * 100 / player.getDuration());
            }
            mHandler.postDelayed(this, TIME_REFRESH_DELAY);
        }
    };




    public void onServiceConnected(MusicPlayerService musicPlayerService){
        for(MusicPlayerServiceCallBack observer : observerArrayList){
            observer.onServiceConnected(musicPlayerService);
        }
    }

    public static void registerObserver(MusicPlayerServiceCallBack observer) {
        if (observerArrayList != null && !observerArrayList.contains(observer))
            observerArrayList.add(observer);
    }

    public interface MusicPlayerServiceCallBack{
        void onMusicPlayBackEnding();
        void onServiceConnected(MusicPlayerService musicPlayerService);
        void updateProgress(int curProgress, int percent);
    }


}
